package com.qny.ai.common;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.nio.charset.StandardCharsets;

/**
 * 密码加密工具类 - 使用SHA-256
 */
public class PasswordUtil {
    
    private static final String SALT = "qiniu_ai_platform_2024";
    
    /**
     * 加密密码
     */
    public static String encode(String rawPassword) {
        try {
            return hashPassword(rawPassword + SALT);
        } catch (Exception e) {
            throw new RuntimeException("密码加密失败", e);
        }
    }
    
    /**
     * 验证密码
     */
    public static boolean matches(String rawPassword, String encodedPassword) {
        try {
            String inputHash = hashPassword(rawPassword + SALT);
            return inputHash.equals(encodedPassword);
        } catch (Exception e) {
            return false;
        }
    }
    
    private static String hashPassword(String password) throws NoSuchAlgorithmException {
        MessageDigest md = MessageDigest.getInstance("SHA-256");
        byte[] hashedPassword = md.digest(password.getBytes(StandardCharsets.UTF_8));
        
        // 转换为十六进制字符串
        StringBuilder sb = new StringBuilder();
        for (byte b : hashedPassword) {
            sb.append(String.format("%02x", b));
        }
        return sb.toString();
    }
}
